$(document).ready(function(){

	var table = $('#student-results tbody');
	
	var form = {
		clear : function(){
			//remove all tr with class with-data
			table.find('tr.with-data').remove();
		},
		set :function(data){
			var template = '';
			$.each(data,function(i,e){
				//if a data with the same id already exist do not show
				if($("tr#id_"+e.id).length == 0)
				{
					template += '<tr id="id_'+e.id+'" class="with-data">';
					template += '<td><input type="checkbox" class="for-login" name="children[]" value="'+e.p_id+'-'+e.id+'"></td>';
					template += '<td>'+ucwords(e.label.toLowerCase())+'</td>';
					template += '</tr>';
				}
			});
			table.append(template).show(500);
		}
	};

	$('input[type=text]#get_students').on('keyup',function(){
		var current = $(this);
		var url = current.attr('url');
		var val = $.trim(current.val());
		
		if(val.length >= 2 && val.length != 0)
		{
			$.ajax({
				type:"post",
				url : url,
				data : {studentname:val}
			}).done(function(result){
				form.clear();
				form.set(result);
			});
		}else{
			console.log('no search');
		}
	});

	$(document).on('click','.for-login',function(){
		if($(this).prop('checked') == true)
		{
			$(this).closest('tr').removeClass('with-data');
		}else{
			$(this).closest('tr').addClass('with-data');
		}
	});
});

function ucwords(str) {
  //  discuss at: http://phpjs.org/functions/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // bugfixed by: Onno Marsman
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld');
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD');
  //   returns 2: 'HELLO WORLD'

  return (str + '')
    .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
      return $1.toUpperCase();
    });
}